package com.weme.live.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat
import com.weme.common.util.startCountdown
import kotlin.math.min

class CountdownColseBar(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {

    companion object {
        private const val MAX_PROGRESS = 10 // 倒计时的总时长（秒）
    }

    private val paint = Paint().apply {
        isAntiAlias = true
        strokeWidth = 8f // 设置圆环的宽度
        color = ContextCompat.getColor(context, com.weme.common.R.color.white)
    }
    private val whitePaint = Paint().apply {
        isAntiAlias = true
        style = Paint.Style.STROKE
        strokeWidth = 4f // 设置圆环的宽度
        color = ContextCompat.getColor(context, com.weme.common.R.color.white) // 未走完的颜色（白色）
    }

    var mCurrentProgress = 0f
    private var currentProgress = MAX_PROGRESS // 当前剩余时间（秒）

    private var customImage: Bitmap? = null // 用于存储自定义图片

    // 在构造函数中加载自定义图片
    init {
        val resourceId = com.example.resources.R.mipmap.icon_live_clone // 替换成你的自定义图片资源
        customImage = BitmapFactory.decodeResource(resources, resourceId)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val centerX = width / 2
        val centerY = height / 2
        val radius = min(centerX, centerY) - 4 // 4 为圆环的宽度的一半

        if(countdownAnimator!=null){
            // 绘制已走完的透明圆环
            canvas.drawArc((centerX - radius).toFloat(), (centerY - radius).toFloat(), (centerX + radius).toFloat(), (centerY + radius).toFloat(), 270 + mCurrentProgress, 360 - mCurrentProgress, false, whitePaint)

        }

        // 绘制自定义图片
        customImage?.let {
            val imageWidth = it.width
            val imageHeight = it.height
            val left = centerX - imageWidth / 2
            val top = centerY - imageHeight / 2
            canvas.drawBitmap(it, left.toFloat(), top.toFloat(), paint)
        }
    }

    // 在类中定义一个可变的属性来存储 ValueAnimator
    private var countdownAnimator: ValueAnimator? = null

    // 开始倒计时
    fun startTime(onCofirm: (() -> Unit)) {
        countdownAnimator = startCountdown(maxProgress = MAX_PROGRESS, // 倒计时总时长（秒）
            onProgressUpdate = { progress ->
                val i = java.lang.Float.valueOf(progress.toString())

                mCurrentProgress = (360 * (i / 100f))
                currentProgress = MAX_PROGRESS - Math.round(i * 0.6f)
                invalidate()
            }, onComplete = {
                onCofirm.invoke()
                onStopTime()
            })
    }
    fun onStopTime(){
        countdownAnimator?.cancel()
        countdownAnimator?.clone()
        countdownAnimator = null
    }


}
